/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package assign2;

import java.io.*;
import java.net.*;
import java.util.ArrayList;

/**
 *
 * @author martyastiadi
 */
public class Server implements Runnable {

    private ArrayList<String> messages = new ArrayList<String>();
    private int localport;

    //private int port;
//    private final int QLEN = 6;

    public Server(int port) {
        setLocalport(port);
    }


    public void run() {
        int visit = 1;
        try {
            ServerSocket listener = new ServerSocket(0);
            Socket serverSocketAccepted;
            while (true) {
                serverSocketAccepted = listener.accept();
                handleConnection(serverSocketAccepted, visit++);
            }
        } catch (IOException e) {
            System.out.println("server listen exception: " + e);
        }
    }

    protected void handleConnection(Socket serverSocketAccepted, int visit)
            throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(serverSocketAccepted.getInputStream()));
        PrintWriter out = new PrintWriter(serverSocketAccepted.getOutputStream(), true);
        out.println("This server has been contacted " + visit + " times.");
        serverSocketAccepted.close();
    }

    public int getLocalport() {
        return (localport);
    }

    protected void setLocalport(int localport) {
        this.localport = localport;
    }
}
